package com.zqq.base

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Gravity
import android.widget.GridLayout
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.zqq.base.dialog.HttpDialog
import com.zqq.base.utils.DpOrPxUtils
import com.zqq.base.utils.LogUtils
import com.zqq.lib_net.NetUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import pub.devrel.easypermissions.EasyPermissions
import java.lang.reflect.ParameterizedType

abstract class BaseActivity<VM:BaseViewModel,VB:ViewDataBinding>:AppCompatActivity(),EasyPermissions.PermissionCallbacks {

    protected lateinit var viewModel: VM
    protected lateinit var viewBinding: VB
    private var noNetDialog:AlertDialog? = null
    private var httpDialog: HttpDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val viewId = setContentViewId()
        if(viewId != 0){
            initVidewDataBinding(viewId)
        }
        ActivityManager.getInstance().addActivity(this)
        initViewModel()
        initDefault()
        checkNet() //检查网络状态
        initFragment(savedInstanceState)
        init()
    }

    private fun initDefault() {
        viewModel?.let {
            it.requestState.observe(this){  //是否显示加载框
                when(it){
                    0 -> dismissHttpDialog()
                    1 -> showHttpDialog()
                }
            }

            it.loadingMsg.observe(this){  //设置加载框的文字
                msg ->
                httpDialog?.let {
                    if(it.isShowing){
                        it.setMsg(msg)
                    }
                }
            }
        }
    }


    open fun showHttpDialog() {
        if (httpDialog != null && httpDialog!!.isShowing()) {
            return
        }
        httpDialog = HttpDialog(this)
        httpDialog!!.show()
    }

    open fun dismissHttpDialog() {
        if (httpDialog != null && httpDialog!!.isShowing()) {
            httpDialog!!.dismiss()
        }
    }

    /**
     * 网络检测 无网络时 显示无网络对话框
     */
    private fun checkNet() {
        viewModel?.let {
            viewModel.isNetConnected.observe(this){
                if(it){
                    noNetDialog?.dismiss()
                }else{
                    showNoNetDialog()
                }
            }
            viewModel.isNetConnected.value =  NetUtils.isNetworkAvailable(this) //打开页面时网络状态
            NetUtils.registerStataCallBack(this){ //网络状态变化监听
                lifecycleScope.launch(Dispatchers.Main) { viewModel.isNetConnected.value = it }
            }
        }
    }

    /**
     * 显示无网络对话框
     */
    private fun showNoNetDialog() {
        if(noNetDialog != null && noNetDialog!!.isShowing){
            return
        }
        val view = layoutInflater.inflate(R.layout.dialog_no_net,null)
        val builder = AlertDialog.Builder(this, R.style.dialog_no_net_style)
        builder.setView(view)
        noNetDialog = builder.create()
        noNetDialog?.show()

        noNetDialog?.let {
            it.window?.let {
                val attributes = it.attributes
                attributes.gravity = Gravity.TOP
                attributes.width = DpOrPxUtils.getScreenWidth(this) *9 / 10
                it.attributes = attributes
            }
        }
    }

    /**
     * 获取viewbinding
     */
    private fun initVidewDataBinding(viewId: Int) {
        viewBinding = DataBindingUtil.setContentView<VB>(this,viewId) //databinding
        viewBinding.lifecycleOwner = this
    }

    /**
     * 获取viewmodel
     */
    @SuppressLint("NewApi")
    private fun initViewModel(){
       val type = javaClass.genericSuperclass //获取当前类的泛型超类类型信息 返回Type对象（通常是ParameterizedType实例）
        if(type != null && type is ParameterizedType){
            val actualTypeArguments = type.actualTypeArguments  // 获取泛型参数数组
            val argument = actualTypeArguments[0] //我们确定是数据第一个数据
            val tClass = argument as Class<VM>
            viewModel = ViewModelProvider(this)[tClass]
        }
    }


    abstract fun setContentViewId(): Int
    open fun initFragment(savedInstanceState: Bundle?) {}
    abstract fun init()


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //将结果转发到EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        onPermissionsGranted(requestCode)
    }

    /**
     * 请求权限结果
     */
    open fun onPermissionsGranted(requestCode: Int) {}

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            for (i in perms.indices) {
                val deniedPermission = perms[i]
                LogUtils.i("bl_main", "onPermissionsDenied>>>" + perms[i])
                onPermissionsDenied(deniedPermission)
            }
        }
    }

    /**
     * 无权限提示
     */
    open fun onPermissionsDenied(deniedPermission: String) {}

    override fun onDestroy() {
        super.onDestroy()
        ActivityManager.getInstance().removeActivity(this)
    }
}